package com.tangcco.lockwell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tangcco.lockwell.base.RestResponse;
import com.tangcco.lockwell.context.WebContext;
import com.tangcco.lockwell.domain.Groups;
import com.tangcco.lockwell.domain.GroupsRelationship;
import com.tangcco.lockwell.domain.User;
import com.tangcco.lockwell.domain.dto.group.GroupDto;
import com.tangcco.lockwell.domain.dto.group.GroupsMembersDto;
import com.tangcco.lockwell.service.GroupsRelationshipService;
import com.tangcco.lockwell.service.GroupsService;
import com.tangcco.lockwell.viewmodel.admin.groups.GroupsMemberVM;
import com.tangcco.lockwell.viewmodel.admin.groups.GroupsPageFindVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.tangcco.lockwell.utility.ConvertCamelToUnderline.bigToSmall;
import static com.tangcco.lockwell.utility.DateToString.dateToString;
import static java.util.Arrays.binarySearch;

/**
 * @author 李金昭
 * 用于处理群组的相关请求
 */

@RequestMapping("/api/admin/groups")
@RestController("AdminGroupsController")
public class GroupsController {
    private final ArrayList<String> arr= new ArrayList<>();
    {
        arr.add("createTime");
        arr.add("modifyTime");
        arr.add("userMax");
        arr.add("groupId");
    }
//    "groupId","createTime","modifyTime","userMax"
    @Resource
    private GroupsService groupsService;
    @Resource
    private WebContext webContext;
    @Resource
    private GroupsRelationshipService groupsRelationshipService;

    @RequestMapping("/delete/{id}")
    public RestResponse deleteById(@PathVariable Integer id){
        groupsService.deleteById(id);
        return RestResponse.ok();
    }
    @RequestMapping("/deleteBusiness/{id}")
    public RestResponse deleteBusiness(@PathVariable Integer id){
        groupsService.updateStatusOn(id);
        return RestResponse.ok();
    }

    @RequestMapping("/findAll/Condition")
    public RestResponse findAllCondition(@RequestBody GroupsPageFindVM groupsPageFindVM){
        PageHelper.startPage(groupsPageFindVM.getPageNum(),groupsPageFindVM.getPageSize());
        List<GroupsPageFindVM> groupsByConditionsSelective = groupsService.findGroupsByConditionsSelective(groupsPageFindVM);
        PageInfo pageInfo = new PageInfo(groupsByConditionsSelective);
        return RestResponse.ok(pageInfo);
    }

    @RequestMapping("/findByTeacher")
    public RestResponse findByTeacher(){
        GroupsPageFindVM groupsPageFindVM = new GroupsPageFindVM();
        groupsPageFindVM.setTeacherId(webContext.getCurrentUser().getUserId());
        groupsPageFindVM.setStatus(1);
        List<GroupsPageFindVM> groupsByConditionsSelective = groupsService.findGroupsByConditionsSelective(groupsPageFindVM);
        List<GroupsMembersDto> result = BeanUtil.copyToList(groupsByConditionsSelective, GroupsMembersDto.class);
        if(CollectionUtils.isEmpty(result)){
            return RestResponse.ok();
        }
        result.forEach(item->{
            List<User> groupsRelationshipList = groupsRelationshipService.findGroupUsersByGroupIdAndUserType(item.getGroupId());
            item.setMembers(groupsRelationshipList);

        });
        return RestResponse.ok(result);
    }
    @RequestMapping("/insert")
    public RestResponse insert(@RequestBody Groups groups){
        if (groups.getGroupId()!=null){
            groups.setModifyTime(dateToString(new Date()));
            groupsService.updateGroupsByIdSelective(groups);
            return RestResponse.ok(groups);
        }
        groups.setCreateTime(dateToString(new Date()));
        groups.setModifyTime(dateToString(new Date()));
        User currentUser = webContext.getCurrentUser();
        groups.setTeacherId(currentUser.getUserId());
        groupsService.insert(groups);
        return RestResponse.ok(groups);
    }

    @RequestMapping("/updateStatus/{id}")
    public RestResponse findAll(@PathVariable Integer id){
        Groups groups = groupsService.selectGroupById(id);
        int status = groups.getStatus();
        if (groups.getStatus()==1){
            groupsService.updateStatusOn(id);
            status = 2;
        }else {
            groupsService.updateStatus(id);
            status = 1;
        }
        return RestResponse.ok(status);
    }

    @RequestMapping("counts")
    public RestResponse counts(){
        return RestResponse.ok(groupsService.selectCountGroups());
    }

    @PostMapping("/findById/{id}")
    public RestResponse findById(@PathVariable Integer id){
        Groups groups = groupsService.selectGroupById(id);
        return RestResponse.ok(groups);
    }
    @PostMapping("/selectByGroupId/{groupId}")
    public RestResponse selectByGroupId(@PathVariable Integer groupId){
        GroupsPageFindVM groups = groupsService.selectByGroupId(groupId);
        return RestResponse.ok(groups);
    }

    //根据群组Id查找群组成员
    @RequestMapping("/findGroupsMember")
    public RestResponse findGroupsMember(@RequestBody GroupsMemberVM groupsMemberVM){
        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(groupsMemberVM.getPageIndex(),groupsMemberVM.getPageSize());
        List<GroupsMemberVM> groupsMemberByGroupId = groupsService.findGroupsMemberByGroupId(groupsMemberVM);
        PageInfo<GroupsMemberVM> pageInfo = new PageInfo<>(groupsMemberByGroupId);
        return RestResponse.ok(pageInfo);
    }

    @RequestMapping("/insertOrUpdateGroup")
    public RestResponse insertOrUpdateGroup(@RequestBody GroupDto groups){
        if (groups.getGroupId()!=null){
            groups.setModifyTime(dateToString(new Date()));
            groupsService.updateGroupsByIdSelective(groups);
            //先删除群组和用户关联数据
            groupsRelationshipService.deleteByGroupId(groups.getGroupId());
            //再插入群组和用户关联数据
            if(groups.getMemberIds()!=null){
                for (Integer memberId : groups.getMemberIds()) {
                    GroupsRelationship rs = new GroupsRelationship();
                    rs.setGroupId(groups.getGroupId());
                    rs.setUserId(memberId);
                    rs.setUserType(15);
                    rs.setStatus(1);
                    rs.setUseraddTime(dateToString(new Date()));
                    groupsRelationshipService.insertSelective(rs);
                }
            }
            return RestResponse.ok(groups);
        }
        groups.setStatus(1);
        groups.setCreateTime(dateToString(new Date()));
        groups.setModifyTime(dateToString(new Date()));
        groups.setTeacherId(webContext.getCurrentUser().getUserId());
        groupsService.insert(groups);
        if(groups.getMemberIds()!=null){
            for (Integer memberId : groups.getMemberIds()) {
                GroupsRelationship rs = new GroupsRelationship();
                rs.setGroupId(groups.getGroupId());
                rs.setUserId(memberId);
                rs.setUserType(15);
                rs.setStatus(1);
                rs.setUseraddTime(dateToString(new Date()));
                groupsRelationshipService.insertSelective(rs);
            }
        }
        return RestResponse.ok(groups);
    }

}
